﻿<?php
define('AUTH_TIMEOUT','300');
define('AUTH_SECRETKEY','daylapassword!@#');
define('AUTH_KEY','teaser_chandai');
define('AUTH_URL','http://id.mgo.vn/');
if(!isset($_SESSION)) session_start();
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * @property api $api 
 * @property User_model $user_model
 */
class Auth extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        //$this->load->model('user_model');
    }

    private function queryString($params, $name = null) {
        $ret = '';
        foreach ($params as $key => $val) {
            if (is_array($val)) {
                if ($name == null)
                    $ret .= queryString($val, $key);
                else
                    $ret .= queryString($val, $name . "[$key]");
            } else {
                if ($name != null)
                    $ret.=$name . "[$key]" . "=$val&";
                else
                    $ret.= "$key=$val&";
            }
        }
        return $ret;
    }

    public function index() {
        $username = $this->session->userdata('username');
        if (empty($username) === true) {
            $this->load->library('crypt');
            $session_id = $this->session->userdata('session_id');
            $params = $_REQUEST;
            $params = $this->security->xss_clean($params);

            if ($params['act'] === 'verify' && $params['data'] && $params['signature']) {
                if (md5($params['data'] . AUTH_SECRETKEY) != $params['signature'])
                    die('Invalid data');
                $data_decrypt = $this->crypt->Decrypt($params['data'], AUTH_SECRETKEY);
                parse_str($data_decrypt, $data_decrypt);
                if (strlen($data_decrypt['token']) === 32) {
                    if ($data_decrypt['data']['time'] + AUTH_TIMEOUT < time()) {
                        $msg = 'Timeout, login again';
                        $url_return = $data_decrypt['data']['return'] ? $data_decrypt['data']['return'] : base_url() . 'auth';
                    } else {
                        if ($data_decrypt['data']['sessionid'] === $session_id) {
                            $username = $data_decrypt['data']['username'];
                            $this->session->set_userdata(
                                    array(
                                        'sessionid' => $session_id,
                                        'username' => $username,
                                    )
                            );
							$_SESSION['USERNAME']=$username;
                            $msg = 'redirect...';
                            //$url_return = base_url();
							$url_return = $data_decrypt['data']['return'] ? $data_decrypt['data']['return'] : base_url() . 'auth';
                        }
                    }
                    redirect($url_return);//'<meta HTTP-EQUIV="REFRESH" content="2; url=' . $url_return . '">';
                }
            } else {
                $data['sessionid'] = $session_id;
                $data['time'] = time();
                $data['return'] = $_SERVER['HTTP_REFERER'];
				if(isset($_GET['unit']) && $_GET['unit']=='gift') $data['return'] = base_url('swap').'?unit=gift';
                $data_querystring = $this->crypt->Encrypt($this->queryString($data), AUTH_SECRETKEY);
                header('Location: ' . AUTH_URL . 'auth?auth=' . urlencode($data_querystring) . '&key=' . AUTH_KEY . '&signature=' . md5($data_querystring . AUTH_SECRETKEY));
            }
        }
        else {
            header('Location: ' . base_url());
        }
    }

    public function logout() {
        $this->session->sess_destroy();
        redirect('home');
    }
	function getgiftcode(){
		$_SESSION['USERNAME']='icarus12345';
		if(isset($_SESSION['USERNAME'])){
			$this->load->model('events/gift_model');
			$username=$_SESSION['USERNAME'];
			$tmp=$this->gift_model->getByUser($username);
			if(isset($tmp[0])){
				$MyInfo=$tmp[0];
				if(isset($MyInfo->UserName) && $MyInfo->UserName==$username){
					$gift=$MyInfo->Giftcode;
					$code=1;
					$msg="$gift";
				}else{
					$params=array(
						"UserName"=>"$username"    
					);
					if($this->gift_model->update($MyInfo->ID, $params)){
						$gift=$MyInfo->Giftcode;
						$code=1;
						$msg="Gift code của bạn là <br/><div class='btngift'>$gift</div>";
					}else{
						$code=-1;
						$msg="Lỗi hệ thống. Vui lòng thử lại sau ít phút.";
					}
				}
			}else{
				$code=-1;
				$msg="Đã hết mã Nhận thưởng. Vui lòng quay lại vào thời gian khác.";
			}
		}else{
			$msg='Bạn chưa đăng nhập.';
		}
		echo json_encode(array('code'=> $msg));
	}
}